from flask import Blueprint, request, render_template, url_for, current_app, flash, redirect
from flask_login import login_required
from app import db
from app.models import Auth
from app.forms import MenuForm

menu_controller = Blueprint("menu", __name__, url_prefix="/admin/menu")

@menu_controller.route("/index")
@login_required
def index():
    menu = Auth.auth_tree()
    return render_template("admin/auth/index.html", menus=menu)

@menu_controller.route('/add', methods=["GET", "POST"])
@login_required
def add():
    form = MenuForm()
    if request.method == "POST":
        if form.validate_on_submit():
            parent_id = request.form.get('parent_id', 0, type=int)
            name = form.name.data
            url = form.url.data
            sort = form.sort.data
            is_menu = request.form.get('is_menu', 1, type=int)
            status = request.form.get('status', 1, type=int)
            try:
                auth = Auth(parent_id=parent_id, name=name,url=url, sort=sort, is_menu=is_menu, status=status)
                db.session.add(auth)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("添加菜单失败")
            return redirect(url_for('menu.index'))
    menu = Auth.auth_tree()
    return render_template("admin/auth/add.html", form=form, menu=menu)

@menu_controller.route('/edit', methods=["GET", "POST"])
@login_required
def edit():
    id = request.args.get('id', 0, type=int)
    try:
        auth = Auth.query.filter_by(id=id).first()
    except Exception as e:
        current_app.logger.error(e)
        flash("菜单不存在")
        return redirect(url_for('menu.index'))

    form = MenuForm(name=auth.name, url=auth.url, sort=auth.sort)
    if request.method == "POST":
        if form.validate_on_submit():
            auth.parent_id = request.form.get('parent_id', 0, type=int)
            auth.name = form.name.data
            auth.url = form.url.data
            auth.sort = form.sort.data
            auth.is_menu = request.form.get('is_menu', 1, type=int)
            auth.status = request.form.get('status', 1, type=int)
            try:
                db.session.add(auth)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("编辑菜单失败")
            return redirect(url_for('menu.index'))
    menu = Auth.auth_tree()
    return render_template("admin/auth/edit.html", form=form, menu=menu, auth=auth)

@menu_controller.route('/delete_op', methods=["GET"])
@login_required
def delete_op():
    id = request.args.get("id")
    if id:
        id_list = id.split(',')
        # 判断是否有下级菜单
        try:
            auths = Auth.query.filter(Auth.parent_id.in_(id_list)).all()
        except  Exception as e:
            current_app.logger.error(e)
            flash("菜单不存在")

        if not auths:
            try:
                Auth.query.filter(Auth.id.in_(id_list)).delete(synchronize_session=False)
                # db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                flash("删除失败")
        else:
            flash("有下级菜单，不能删除")
    else:
        flash("请选择要删除的项")
    return redirect(url_for(".index"))